package handlers

import (
	"book-world/cache"
	"book-world/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "不能为空",
		})
		return
	}
	data := models.User{
		Username: username,
		Password: password,
	}
	err := models.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "添加失败",
		})
		return
	}
	var port models.User
	models.DB.Where("id = ?", data.ID).First(&port)
	jsonData, _ := json.Marshal(port)
	redis_data_key := "post_" + strconv.Itoa(int(data.ID))
	cache.Rdb.Set(cache.Ctx, redis_data_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func BookList(c *gin.Context) {
	var book []models.Book
	redis_data_key := "port_list"
	cacheDate, _ := cache.Rdb.Get(cache.Ctx, redis_data_key).Result()
	if cacheDate == "" {
		models.DB.Find(&book)
		jsonData, _ := json.Marshal(book)
		cache.Rdb.Set(cache.Ctx, redis_data_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheDate), &book)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": book,
		"msg":  "success",
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var books models.Book

	redis_key := "book_detail_" + id
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheJson == "" {
		models.DB.Where("id = ?", id).First(&books)
		json, _ := json.Marshal(books)
		cache.Rdb.Set(cache.Ctx, redis_key, json, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheJson), &books)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": books,
		"msg":  "detail",
	})
	return
}
